package ru.spbsu.electromenu.servlet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import ru.spbsu.electromenu.model.Alert;
import ru.spbsu.electromenu.serialization.DeserializationException;
import ru.spbsu.electromenu.service.AlertService;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Date: 3/23/11
 * Time: 9:31 PM
 *
 * @author Artem Titov
 */
public class SendAlertServlet extends ClientHttpServlet {
    private static final Logger logger = LoggerFactory.getLogger(SendAlertServlet.class);

    private AlertService alertService;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        alertService = getBean("alertService");
        if (alertService == null) {
            logger.error("Failed to instantiate necessary services");
            isValid = false;
            throw new IllegalStateException("Failed to instantiate necessary services");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if (!isValid) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }
        try {
            final MultipartResolver multipartResolver = new CommonsMultipartResolver();
            if (multipartResolver.isMultipart(request)) {
                request = multipartResolver.resolveMultipart(request);
            }
            final Alert alert = deserializer.deserializeAlert(request.getParameter("request"));

            alertService.put(alert);

            response.setStatus(HttpServletResponse.SC_OK);
        } catch (DeserializationException e) {
            logger.error("Failed to deserialize alert", e);
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        } catch (Exception e) {
            logger.error("Internal fail", e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } catch (Throwable t) {
            logger.error("Unexpected fail", t);
        }
    }
}
